package com.mmall.service.impl;

import com.google.common.collect.Lists;
import com.mmall.service.IFileService;
import com.mmall.utils.FtpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service("iFileService")
public class FileServiceImpl implements IFileService{

    private Logger logger= LoggerFactory.getLogger(FileServiceImpl.class);

    //上传文件并且将文件名返回给前端
    public String upload(MultipartFile file,String path){

        String fileName=file.getOriginalFilename();
        //获得扩展名 abc.jpg-->jpg
        String extensionName=fileName.substring(fileName.lastIndexOf(".")+1);
        String uploadFileName= UUID.randomUUID().toString()+"."+extensionName;
        logger.info("开始上传文件,上传文件的文件名:{},上传的路径:{},上传文件的新文件名:{}",fileName,path,uploadFileName);
        File fileDir=new File(path);
        if (!fileDir.exists()){
            fileDir.setWritable(true);
            fileDir.mkdirs();
        }
        File targetFile=new File(path,uploadFileName);
        try {
            file.transferTo(targetFile);

            //这里文件已经上传成功了
            //将上传成功的文件上传到ftp服务器上
            FtpUtil.uploadFile(Lists.newArrayList(targetFile));
            //将tomcat webapp下面的文件夹删除掉
            targetFile.delete();
        } catch (IOException e) {
            logger.error("上传文件异常: ",e);
            return null;
        }

        return targetFile.getName();
    }
}
